<template>
  <navbar />
  <div class="main-container">
    <!-- 页面头部（保持与系统模块一致的样式与结构） -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">{{ $route.meta.title || '机构管理' }}</h2>
      </div>
      <div class="header-right">
        <el-button
          class="add-btn op-btn"
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:tenant:add']"
          >新增</el-button
        >
      </div>
    </div>

    <!-- 查询表单区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <!-- 机构编码精确查询 -->
      <el-form-item label="机构编码" prop="tenantCode">
        <el-input
          v-model="queryParams.tenantCode"
          placeholder="请输入机构编码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 机构名称模糊查询 -->
      <el-form-item label="机构名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入机构名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tenantList">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="80" align="center" />
        <!-- logo缩略图展示列 -->
        <el-table-column label="Logo" width="120" align="center">
          <template #default="scope">
            <img v-if="scope.row.logoUrl" :src="resolveLogo(scope.row.logoUrl)" class="logo-thumb" alt="logo" />
          </template>
        </el-table-column>
        <!-- 机构编码列 -->
        <el-table-column prop="tenantCode" label="机构编码" min-width="160" align="center" />
        <!-- 机构名称列 -->
        <el-table-column
          prop="tenantName"
          label="机构名称"
          min-width="200"
          align="center"
          :show-overflow-tooltip="true"
        />
        <!-- 操作列：编辑/删除 -->
        <el-table-column label="操作" align="center" width="210" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenant:edit']"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:tenant:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件（与系统用户等列表保持一致风格） -->
    <div class="queryParams-container">
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="tenantRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <!-- 机构编码：必填，长度≤20 -->
          <el-col :span="24">
            <el-form-item label="机构编码" prop="tenantCode">
              <el-input v-model="form.tenantCode" placeholder="请输入机构编码" maxlength="20" />
            </el-form-item>
          </el-col>
          <!-- 机构名称：必填，长度≤50 -->
          <el-col :span="24">
            <el-form-item label="机构名称" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="请输入机构名称" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- 机构Logo：图片上传，限定JPG/PNG，大小≤5MB，限制数量1 -->
          <el-col :span="24">
            <el-form-item label="机构Logo" prop="logoUrl">
              <ImageUpload
                v-model="form.logoUrl"
                :limit="1"
                :file-size="5"
                :file-type="['png', 'jpg']"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tenants">
import {
  listTenant,
  getTenant,
  addTenant,
  updateTenant,
  delTenant,
  checkTenantCodeUnique,
  checkTenantNameUnique
} from '@/api/system/tenants'

// 获取当前组件实例，用于调用全局工具（字典、消息、重置表单等）
const { proxy } = getCurrentInstance()

// 列表数据与UI状态
const tenantList = ref([])
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const open = ref(false)
const title = ref('')
// 编辑态下记录原始值，用于唯一性校验时跳过未变更的字段
const original = reactive({ code: '', name: '' })

// 查询参数、表单数据与校验规则
const data = reactive({
  form: {
    id: undefined,
    tenantCode: '',
    tenantName: '',
    logoUrl: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantCode: undefined,
    tenantName: undefined
  },
  rules: {
    tenantCode: [
      { required: true, message: '机构编码不能为空', trigger: 'blur' },
      { min: 1, max: 20, message: '机构编码长度需在 1-20 之间', trigger: 'blur' },
      {
        // 远程唯一性校验（返回 data：0-不存在，1-存在）
        validator: (rule, value, callback) => {
          if (!value) return callback()
          // 未变更则跳过校验
          if (form.value.id && value === original.code) return callback()
          checkTenantCodeUnique(value)
            .then(res => {
              const exists = Number(res.data) === 1
              if (exists) {
                // 提醒：编码已存在
                return callback(new Error('机构编码已存在'))
              }
              callback()
            })
            .catch(() => {
              // 异常时放行但提示错误
              callback()
            })
        },
        trigger: ['blur']
      }
    ],
    tenantName: [
      { required: true, message: '机构名称不能为空', trigger: 'blur' },
      { min: 1, max: 50, message: '机构名称长度需在 1-50 之间', trigger: 'blur' },
      {
        // 远程唯一性校验（返回 data：0-不存在，1-存在）
        validator: (rule, value, callback) => {
          if (!value) return callback()
          if (form.value.id && value === original.name) return callback()
          checkTenantNameUnique(value)
            .then(res => {
              const exists = Number(res.data) === 1
              if (exists) {
                return callback(new Error('机构名称已存在'))
              }
              callback()
            })
            .catch(() => {
              callback()
            })
        },
        trigger: ['blur']
      }
    ],
    logoUrl: [{ required: true, message: '请上传机构Logo', trigger: 'change' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 列表查询
function getList() {
  loading.value = true
  listTenant(queryParams.value)
    .then(res => {
      tenantList.value = res.rows || res.data || []
      total.value = res.total || (Array.isArray(tenantList.value) ? tenantList.value.length : 0)
    })
    .finally(() => {
      loading.value = false
    })
}

// 重置表单
function reset() {
  form.value = {
    id: undefined,
    tenantCode: '',
    tenantName: '',
    logoUrl: ''
  }
  proxy.resetForm('tenantRef')
}

// 取消对话框
function cancel() {
  open.value = false
  reset()
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 重置搜索
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 新增
function handleAdd() {
  reset()
  open.value = true
  title.value = '新增机构'
  original.code = ''
  original.name = ''
}

// 编辑
function handleUpdate(row) {
  reset()
  getTenant(row.id).then(response => {
    form.value = {
      id: response.data?.id ?? row.id,
      tenantCode: response.data?.tenantCode ?? row.tenantCode,
      tenantName: response.data?.tenantName ?? row.tenantName,
      logoUrl: response.data?.logoUrl ?? row.logoUrl ?? ''
    }
    // 记录原始值
    original.code = form.value.tenantCode
    original.name = form.value.tenantName
    open.value = true
    title.value = '编辑机构'
  })
}

// 提交
function submitForm() {
  proxy.$refs['tenantRef'].validate(valid => {
    if (!valid) return
    const submitter = form.value.id != null ? updateTenant : addTenant
    submitter(form.value).then(() => {
      proxy.$modal.notifySuccess(form.value.id != null ? '修改成功' : '新增成功')
      open.value = false
      getList()
    })
  })
}

// 删除
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除机构 "' + row.tenantName + '" ?')
    .then(() => delTenant(row.id))
    .then(() => {
      proxy.$modal.notifySuccess('删除成功')
      getList()
    })
    .catch(() => {})
}

// 解析logo地址（兼容相对路径与绝对路径）
function resolveLogo(url) {
  if (!url) return ''
  const base = import.meta.env.VITE_APP_BASE_API
  // 简单兼容：若为绝对路径直接返回，否则拼接base
  if (/^https?:\/\//.test(url)) return url
  return (base || '') + url
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.logo-thumb {
  width: 48px;
  height: 48px;
  object-fit: contain;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  background-color: #fafafa;
}
</style>
